import React, { useState, useEffect } from 'react';
import {
  Card,
  Descriptions,
  Tag,
  Button,
  Space,
  Typography,
  Row,
  Col,
  List,
  Form,
  Input,
  message,
  Divider,
  Table,
  Avatar,
  Popconfirm,
} from 'antd';
import {
  DownloadOutlined,
  LikeOutlined,
  MessageOutlined,
  FileOutlined,
  UserOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import { getTorrentDetail, downloadTorrent, deleteTorrent } from '../../api/torrent';
import { getTorrentComments, addComment, likeComment, unlikeComment } from '../../api/comment';
import { TorrentDetail, Comment as CommentType, PageResult } from '../../types';
import { formatBytes, formatDateTime } from '../../utils/format';
import { useAuth } from '../../context/AuthContext';
import { getDailyDownloadLimit } from '../../api/user';

const { Title, Text } = Typography;
const { TextArea } = Input;

const TorrentDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { user } = useAuth();
  const [torrent, setTorrent] = useState<TorrentDetail | null>(null);
  const [comments, setComments] = useState<CommentType[]>([]);
  const [loading, setLoading] = useState(true);
  const [commentLoading, setCommentLoading] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    if (id) {
      fetchTorrentDetail();
      fetchComments();
    }
  }, [id]);

  const fetchTorrentDetail = async () => {
    try {
      const response = await getTorrentDetail(Number(id));
      if (response.code === 200) {
        setTorrent(response.data);
      }
    } catch (error) {
      console.error('获取种子详情失败:', error);
      message.error('获取种子详情失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchComments = async () => {
    try {
      const response = await getTorrentComments(Number(id));
      if (response.code === 200) {
        setComments(response.data.records || []);
      }
    } catch (error) {
      console.error('获取评论失败:', error);
    }
  };

  const handleDownload = async () => {
    if (!torrent) return;
    
    try {
      const response = await downloadTorrent(torrent.id);
      
      // 先更新下载限制，因为后端在发送文件前已经更新了计数
      const limitResponse = await getDailyDownloadLimit();
      if (limitResponse.code === 200) {
        // 通过全局事件通知TorrentList组件更新
        window.dispatchEvent(new CustomEvent('updateDailyDownloadLimit'));
      }
      
      const blob = new Blob([response], { type: 'application/x-bittorrent' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `${torrent.title}.torrent`;
      document.body.appendChild(link);
      link.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(link);
      message.success('种子文件下载成功');
    } catch (error) {
      console.error('下载种子失败:', error);
      message.error('下载种子失败');
      // 如果下载失败，也要重新获取限制，因为可能是达到限制导致的
      const limitResponse = await getDailyDownloadLimit();
      if (limitResponse.code === 200) {
        window.dispatchEvent(new CustomEvent('updateDailyDownloadLimit'));
      }
    }
  };

  const handleDelete = async () => {
    if (!torrent) return;
    
    try {
      await deleteTorrent(torrent.id);
      message.success('种子删除成功');
      navigate('/torrents');
    } catch (error) {
      console.error('删除种子失败:', error);
      message.error('删除种子失败');
    }
  };

  // 检查是否有删除权限
  const canDelete = () => {
    if (!user || !torrent) return false;
    // 管理员（等级4）或种子上传者可以删除
    return user.userClass >= 4 || torrent.uploaderId === user.id;
  };

  const handleAddComment = async (values: { content: string }) => {
    try {
      setCommentLoading(true);
      const response = await addComment({
        torrentId: Number(id),
        content: values.content,
      });
      if (response.code === 200) {
        message.success('评论发表成功');
        form.resetFields();
        fetchComments();
      }
    } catch (error) {
      console.error('发表评论失败:', error);
      message.error('发表评论失败');
    } finally {
      setCommentLoading(false);
    }
  };

  const handleLikeComment = async (commentId: number, isLiked: boolean) => {
    try {
      if (isLiked) {
        await unlikeComment(commentId);
        message.success('已取消点赞');
      } else {
        await likeComment(commentId);
        message.success('点赞成功');
      }
      fetchComments();
    } catch (error) {
      console.error('操作失败:', error);
      message.error('操作失败');
    }
  };

  const getPromotionTag = (promotionStatus: number) => {
    switch (promotionStatus) {
      case 1:
        return <Tag color="green">免费下载</Tag>;
      case 2:
        return <Tag color="blue">2x上传</Tag>;
      case 3:
        return <Tag color="red">2x下载</Tag>;
      case 4:
        return <Tag color="purple">50%下载</Tag>;
      default:
        return null;
    }
  };

  const fileColumns = [
    {
      title: '文件路径',
      dataIndex: 'path',
      key: 'path',
      render: (path: string) => (
        <Space>
          <FileOutlined />
          <Text>{path}</Text>
        </Space>
      ),
    },
    {
      title: '文件大小',
      dataIndex: 'size',
      key: 'size',
      width: 120,
      render: (size: number) => formatBytes(size),
    },
  ];

  if (loading) {
    return <Card loading={true} />;
  }

  if (!torrent) {
    return (
      <Card>
        <Text type="secondary">种子不存在或已被删除</Text>
      </Card>
    );
  }

  return (
    <div>
      <Card
        title={
          <Space>
            <Title level={3}>{torrent.title}</Title>
            {torrent.promotionStatus !== undefined && getPromotionTag(torrent.promotionStatus)}
          </Space>
        }
        extra={
          <Space>
            <Button
              type="primary"
              icon={<DownloadOutlined />}
              onClick={handleDownload}
            >
              下载种子
            </Button>
            {canDelete() && (
              <Popconfirm
                title="确定要删除这个种子吗？"
                description="删除后无法恢复，请谨慎操作！"
                onConfirm={handleDelete}
                okText="确定"
                cancelText="取消"
              >
                <Button
                  type="primary"
                  danger
                  icon={<DeleteOutlined />}
                >
                  删除种子
                </Button>
              </Popconfirm>
            )}
          </Space>
        }
      >
        <Row gutter={24}>
          <Col span={16}>
            <Descriptions title="种子信息" bordered column={2}>
              <Descriptions.Item label="分类">
                <Tag color="blue">{torrent.category}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="文件大小">
                {formatBytes(torrent.fileSize || torrent.size || 0)}
              </Descriptions.Item>
              <Descriptions.Item label="上传者">
                {torrent.uploader || torrent.uploaderName}
              </Descriptions.Item>
              <Descriptions.Item label="上传时间">
                {formatDateTime(torrent.createdTime || torrent.uploadedAt || '')}
              </Descriptions.Item>
              <Descriptions.Item label="做种数">
                <Text type="success">{torrent.seeders}</Text>
              </Descriptions.Item>
              <Descriptions.Item label="下载数">
                <Text type="warning">{torrent.leechers}</Text>
              </Descriptions.Item>
              <Descriptions.Item label="完成数">
                {torrent.finished || torrent.completedCount}
              </Descriptions.Item>
              <Descriptions.Item label="促销状态">
                {torrent.promotionStatus !== undefined ? getPromotionTag(torrent.promotionStatus) : '无'}
              </Descriptions.Item>
            </Descriptions>

            {torrent.description && (
              <div style={{ marginTop: 24 }}>
                <Title level={4}>种子描述</Title>
                <Card>
                  <Text style={{ whiteSpace: 'pre-wrap' }}>
                    {torrent.description}
                  </Text>
                </Card>
              </div>
            )}
          </Col>
          <Col span={8}>
            <Card title="健康度统计" size="small">
              <Space direction="vertical" style={{ width: '100%' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <Text>做种用户:</Text>
                  <Text type="success" strong>{torrent.seeders}</Text>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <Text>下载用户:</Text>
                  <Text type="warning" strong>{torrent.leechers}</Text>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <Text>完成下载:</Text>
                  <Text strong>{torrent.finished || torrent.completedCount || 0}</Text>
                </div>
              </Space>
            </Card>
          </Col>
        </Row>
      </Card>

      {/* 文件列表 */}
      {torrent.files && torrent.files.length > 0 && (
        <Card title="文件列表" style={{ marginTop: 16 }}>
          <Table
            columns={fileColumns}
            dataSource={torrent.files}
            rowKey="path"
            pagination={false}
            size="small"
          />
        </Card>
      )}

      {/* NFO信息 */}
      {torrent.hasNfo && (
        <Card title="NFO信息" style={{ marginTop: 16 }}>
          <pre style={{ 
            whiteSpace: 'pre-wrap', 
            wordWrap: 'break-word',
            fontFamily: 'monospace',
            backgroundColor: '#f5f5f5',
            padding: 16,
            borderRadius: 4,
          }}>
            {torrent.nfoContent}
          </pre>
        </Card>
      )}

      {/* 评论区 */}
      <Card 
        title={
          <Space>
            <MessageOutlined />
            <span>评论 ({comments.length})</span>
          </Space>
        }
        style={{ marginTop: 16 }}
      >
        <Form form={form} onFinish={handleAddComment}>
          <Form.Item
            name="content"
            rules={[{ required: true, message: '请输入评论内容' }]}
          >
            <TextArea
              rows={4}
              placeholder="发表您的评论..."
            />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={commentLoading}
            >
              发表评论
            </Button>
          </Form.Item>
        </Form>

        <Divider />

        <List
          dataSource={comments}
          renderItem={(comment) => (
            <List.Item
              key={comment.id}
              actions={[
                <Button
                  key="like"
                  type="text"
                  icon={<LikeOutlined />}
                  style={{ color: comment.isLiked ? '#1890ff' : undefined }}
                  onClick={() => handleLikeComment(comment.id, comment.isLiked || false)}
                >
                  {comment.isLiked ? '已点赞' : '点赞'} ({comment.likes || comment.likeCount || 0})
                </Button>
              ]}
            >
              <List.Item.Meta
                avatar={<Avatar icon={<UserOutlined />} />}
                title={
                  <Space>
                    <Text strong>{comment.username}</Text>
                    <Text type="secondary" style={{ fontSize: '12px' }}>
                      {formatDateTime(comment.createdTime || comment.createdAt || '')}
                    </Text>
                  </Space>
                }
                description={<Text>{comment.content}</Text>}
              />
            </List.Item>
          )}
        />
      </Card>
    </div>
  );
};

export default TorrentDetailPage; 